package com.hzj.rtsp.task;

import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;

/**
 * Created by admin on 2019-9-16.
 */
public class SpringContextHolder {
    public static ApplicationContext applicationContext = null;


    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {
        return (T) applicationContext.getBean(name);
    }
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name,Class<T> requiredType) {
        return (T) applicationContext.getBean(name,requiredType);
    }
    /**
     * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
     */
    public static <T> T getBean(Class<T> requiredType) {
        assertContextInjected();
        return applicationContext.getBean(requiredType);
    }

    /**
     * 检查ApplicationContext不为空.
     */
    private static void assertContextInjected() {
        if (applicationContext == null) {
            throw new IllegalStateException("applicaitonContext未注入,请在applicationContext.xml中定义SpringContextHolder");
        }
    }
    /**
     * 实现DisposableBean接口,在Context关闭时清理静态变量.
     */

    public static void clear() {
        //logger.debug("清除SpringContextHolder中的ApplicationContext:" + applicationContext);
        applicationContext = null;
    }

    public  static Environment getEnviroment(){
        return applicationContext.getEnvironment();
    }

    public  static String getProperty(String key){

        return getEnviroment().getProperty(key);
    }

    public static Resource getResource(String s){
        return applicationContext.getResource(s);
    }
}
